<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="工厂" prop="factory">
        <el-select
          v-model="queryParams.factory"
          placeholder="请选择工厂"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('factory')"
        >
          <el-option
            v-for="(item, index) in factoryOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工段" prop="workshopCode">
        <el-select
          v-model="queryParams.workshopCode"
          placeholder="请选择工段"
          clearable
          filterable
          style="width: 240px"
          @change="handleSearchListChange('workSection')"
        >
          <el-option
            v-for="(item, index) in workshopOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产线" prop="lineCode">
        <el-select
          v-model="queryParams.lineCode"
          placeholder="请选择产线"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('productLine')"
        >
          <el-option
            v-for="(item, index) in lineOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工艺段" prop="sectionCode">
        <el-select
          v-model="queryParams.sectionCode"
          placeholder="请选择工艺段"
          style="width: 240px"
          clearable
          filterable
          @change="handleSearchListChange('sectionCode')"
        >
          <el-option
            v-for="(item, index) in processOptions"
            :key="index"
            :label="item.deptName"
            :value="item.deptCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行人" prop="userNames">
        <el-input
          v-model="queryParams.userNames"
          placeholder="请输入执行人"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="时间段" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          style="width: 240px"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="(item, index) in task_record_status"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      style="width: 100%"
      max-height="500px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="任务ID"
        prop="taskRecordDetailId"
        :show-overflow-tooltip="true"
        width="140"
      >
        <template #default="scope">
          <el-link
            v-hasPermi="['produce:feeding:query']"
            type="primary"
            @click="goDetail(scope.row)"
          >
            {{ scope.row.taskRecordDetailId }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column width="100px" label="任务名称" prop="taskName" />
      <el-table-column width="100px" label="执行人" prop="userNames">
        <template #default="scope">
          <span>{{ scope.row.workStationName + "(" + scope.row.userNames + ")" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="status" :show-overflow-tooltip="true" width="140">
        <template #default="scope">
          <dict-tag :options="task_record_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column width="100px" label="任务时间" prop="taskTimeStart">
        <template #default="scope">
          <span>{{ scope.row.taskTimeStart + "-" + scope.row.taskTimeEnd }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100px" label="处理时间" prop="processTime" />
      <!-- <el-table-column width="100px" label="任务类型" prop="taskType" /> -->
      <el-table-column label="任务类型" prop="taskType" :show-overflow-tooltip="true" width="140">
        <template #default="scope">
          <dict-tag :options="task_template_type" :value="scope.row.taskType" />
        </template>
      </el-table-column>
      <el-table-column width="100px" label="订单编号" prop="orderCode" />
      <el-table-column width="60px" label="班次" prop="classesName" />
      <el-table-column width="170px" label="班组" prop="workGroupName" />
      <el-table-column width="100px" label="工厂" prop="factoryName" />
      <el-table-column width="130px" label="工段" prop="workshopName" />
      <el-table-column width="130px" label="产线" prop="productLineName" />
      <el-table-column width="130px" label="工艺段" prop="sectionName" />
      <el-table-column
        label="操作"
        align="center"
        width="120"
        fixed="right"
        class-name="small-padding fixed-width"
      >
        <!-- v-if="scope.row.status == 1" -->
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="['1', '2'].includes(scope.row.status)"
            icon="Edit"
            v-hasPermi="['produce:taskRecord:getExecuteList']"
            @click="handleUpdate(scope.row)"
          >
            执行
          </el-button>
          <el-button
            link
            type="primary"
            v-if="['1', '2'].includes(scope.row.status)"
            icon="Edit"
            v-hasPermi="['produce:taskRecord:batchCloseTask']"
            @click="close(scope.row)"
          >
            关闭
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 关闭 -->
    <el-dialog :close-on-click-modal="false" v-model="dialogClose" title="关闭任务" width="600">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="关闭原因" prop="reason">
          <el-select v-model="ruleForm.reason" placeholder="请选择关闭原因">
            <el-option
              v-for="(item, index) in shutdown_reason"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" maxlength="200" show-word-limit placeholder="请填写说明" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogClose = false">取 消</el-button>
          <el-button type="primary" @click="confirmClose">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="changeShifts">
import { listTaskRecord, batchCloseTask } from "@/api/productionMgt/taskCenter";

import { ref, reactive, toRefs, onMounted, getCurrentInstance } from "vue";
import { depeIdSelectList } from "@/api/system/dept";
import DataInfo from "./data";
import ViewInfo from "./view";

const { proxy } = getCurrentInstance();
const { task_record_status } = proxy.useDict("task_record_status");
const { shutdown_reason } = proxy.useDict("shutdown_reason");
const { task_template_type } = proxy.useDict("task_template_type");
const typeList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref([]);
var factoryOptions = ref([]);
var workshopOptions = ref([]);
var lineOptions = ref([]);
var processOptions = ref([]);
const dialogClose = ref(false);
const ruleFormRef = ref();
const closeInfo = ref({});
const ruleForm = reactive({
  reason: "",
  remark: "",
});
const validateRemark = (rule, value, callback) => {
  if (value === "" && ["1", "2"].includes(ruleForm.reason)) {
    callback(new Error("请填写关闭原因"));
  } else {
    callback();
  }
};
const rules = reactive({
  reason: [
    {
      required: true,
      message: "请选择关闭原因",
      trigger: "change",
    },
  ],
  remark: [{ validator: validateRemark, trigger: "blur" }],
});
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
});

// 关闭
function close(row) {
  closeInfo.value = row;
  ruleForm.reason = "";
  ruleForm.remark = "";
  dialogClose.value = true;
}
function confirmClose() {
  ruleFormRef.value.validate((valid) => {
    console.log(valid);
    batchCloseTask({
      taskRecordDetailIds: [closeInfo.value.taskRecordDetailId],
      closeReason: ruleForm.reason,
      remark: ruleForm.remark,
    }).then((res) => {
      console.log(res);
      dialogClose.value = false;
      proxy.$modal.msgSuccess("关闭成功");
      getList();
    });
  });
}

const { queryParams } = toRefs(data);
/** 查询设备类型列表 */
function getList() {
  loading.value = true;
  let newForm = JSON.parse(JSON.stringify(queryParams.value));
  if (queryParams.value?.date?.length) {
    newForm.taskTimeStart = queryParams.value.date[0] + " 00:00:00";
    newForm.taskTimeEnd = queryParams.value.date[1] + " 23:59:59";
    delete newForm.date;
  }
  listTaskRecord(proxy.addDateRange(newForm)).then((response) => {
    typeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getFactorys() {
  // getFactoryTree(query).then((res) => {
  //   factoryOptions.value = res.data;
  // });
  depeIdSelectList({
    deptType: "factory",
    deptCode: "",
    permissionType: "permission",
  }).then((res) => {
    factoryOptions.value = res.data;
  });
}

function handleSearchListChange(type) {
  if (type == "factory") {
    depeIdSelectList({
      deptType: "station",
      deptCode: queryParams.value.factory,
      permissionType: "permission",
    }).then((res) => {
      workshopOptions.value = res.data;
      lineOptions.value = [];
      processOptions.value = [];
      queryParams.value.workshopCode = "";
      queryParams.value.lineCode = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "workSection") {
    depeIdSelectList({
      deptType: "line",
      deptCode: queryParams.value.workshopCode,
      permissionType: "permission",
    }).then((res) => {
      lineOptions.value = res.data;
      processOptions.value = [];
      queryParams.value.lineCode = "";
      queryParams.value.sectionCode = "";
    });
  }
  if (type == "productLine") {
    depeIdSelectList({
      deptType: "craft",
      deptCode: queryParams.value.lineCode,
      permissionType: "permission",
    }).then((res) => {
      processOptions.value = res.data;
      queryParams.value.sectionCode = "";
    });
  }
}
// function handleDetailhas(row) {
//   proxy.subPage(HandoverData, {
//     title: "交接班详情",
//     data: { ...row, parentType: "view" },
//   });
// }

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.status = "";
  handleQuery();
}

/** 任务填报 */
function handleUpdate(row) {
  proxy.subPage(DataInfo, { title: "任务填报", data: { ...row, parentType: "add" } }, () => {
    getList();
  });
}
/** 详情 */
function goDetail(row) {
  proxy.subPage(ViewInfo, { title: "任务详情", data: { ...row, parentType: "view" } }, () => {
    getList();
  });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

getList();
getFactorys();
onMounted(async () => {
  getList();
});
</script>
